package pure.engine.world 
{
	import flash.geom.Point;
	/**
	 * ...
	 * @author Pure
	 */
public class PathWorld extends TiledWorldContent 
{
	
	public function PathWorld(landformData:Array, tileSize:int) 
	{
		super(landformData, tileSize);
		
		_addFindingPath();
	
		_pointCacheA = new Point();
		_pointCacheB = new Point();
	}

	
	
	protected var _path:Path;    // 寻路
	protected var _pathMode:String;
	
	protected var _pointCacheA:Point;
	protected var _pointCacheB:Point;
	
	
	/**
	 * [取]是否可通过
	 * @param posX
	 * @param posY
	 */
	public function getWalkable(posX:int, posY:int):Boolean
	{
		if (!_path) return true;
		
		var tmpX:int = _getTileX(posX);
		var tmpY:int = _getTileY(posY);
		return _path.getWalkable(tmpX, tmpY);
	}
	
	/**
	 * [存]是否可通过
	 * @param posX
	 * @param posY
	 * @param b
	 */
	public function setWalkable(posX:int, posY:int, b:Boolean):void {
		if (!_path) return;
		
		var tmpX:int = _getTileX(posX);
		var tmpY:int = _getTileY(posY);
		_path.setWalkable(tmpX, tmpY, b);
	}
	
	

	/**
	 * 寻路
	 * @param startPos
	 * @param endPos
	 */
	public function findPath(startPos:Point, endPos:Point):Array
	{
		if (!_path) return null;
		
		_pointCacheA.x = _getTileX(startPos.x);
		_pointCacheA.y = _getTileY(startPos.y);
		
		_pointCacheB.x = _getTileX(endPos.x);
		_pointCacheB.y = _getTileY(endPos.y);
		
		var list:Array = [];
		if(_path.findPath(_pointCacheA,_pointCacheB)) {
			var pathData:Array = _path.pathData;
			var len:int = pathData.length;
			for (var i:int = 0; i < len; i++) {
				list[i] = new Point((pathData[i].x + 0.5) * _tileSize, (pathData[i].y + 0.5) * _tileSize);
			}
			
			list.pop();
			list.push(endPos);
			
			// 移除第一节点
			list.shift();
			return list;
		}
		return null;
	}
	
	
	
		 
	protected function _addFindingPath():void
	{
		_path = new Path(_columns, _rows);
		
		// 地形数据存在
		if (_landformData != null) {
			var lenY:int = _landformData.length;
			for (var y:int = 0; y < lenY; y++) {
				var lenX:int = _landformData[0].length;
				for (var x:int = 0; x < lenX; x++) {
					// 地形数据 >0 ，都为不可通过
					if (_landformData[y][x] > 0) _path.setWalkable(x, y, false );
				}
			}
		}
	}
	
}

}